﻿using System;
using System.IO;
using System.ServiceModel.Activation;
using appDataContracts;
using appInterfaces;

namespace appServices
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class PictureService : IPictureService
    {
        private string serveurPath = "C:\\inetpub\\wwwroot\\DADNET\\AlFiNoReKou\\Client";
        public bool Upload(SerializedPictureFile picture)
        {
            FileStream fileStream = null;
            BinaryWriter writer = null;
            string filePath;

            try
            {
                filePath = serveurPath + "\\Upload\\" + picture.PictureName;
                // HttpContext.Current.Server.MapPath(".")

                if (picture.PictureName != string.Empty)
                {
                    fileStream = File.Open(filePath, FileMode.Create);
                    writer = new BinaryWriter(fileStream);
                    writer.Write(picture.PictureStream);
                }

                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            }
            finally
            {
                if (fileStream != null)
                    fileStream.Close();
                if (writer != null)
                    writer.Close();
            }
        }

        public SerializedPictureFile Download(string pictureName)
        {
            FileStream fileStream = null;
            BinaryReader reader = null;
            string imagePath;
            byte[] imageBytes;

            try
            {
                imagePath = serveurPath + "\\Upload\\" + pictureName;

                if (File.Exists(imagePath))
                {
                    fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
                    reader = new BinaryReader(fileStream);

                    imageBytes = reader.ReadBytes((int)fileStream.Length);

                    return new SerializedPictureFile() { PictureName = pictureName, PictureStream = imageBytes };
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
